package com.jz.banner.screen.services

import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.*
import com.blankj.utilcode.util.NetworkUtils
import com.jz.banner.screen.R
import com.jz.banner.screen.banner.net.BannerApi
import com.jz.banner.screen.banner.ui.BannerActivity
import com.jz.banner.screen.banner.utils.ActivityUtils
import com.jz.banner.screen.bean.*
import com.jz.banner.screen.ui.App
import com.jz.banner.screen.ui.activity.LoginActivity
import com.jz.banner.screen.utils.*
import com.jz.banner.screen.utils.eventbus.Event
import com.jz.banner.screen.utils.eventbus.EventBusUtil
import com.jz.banner.screen.utils.eventbus.EventCode
import com.jz.banner.screen.utils.eventbus.EventCode.Companion.TOAST_MESSAGE
import com.jz.banner.screen.voice.VoicePlay
import com.jz.banner.screen.voice.constant.VoiceConstants
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit


@SuppressLint("StaticFieldLeak")
class AppService : Service() {
    companion object {
        var mCountUpdateApp = 1L;
        var mIsNetworkConnect = false //是否网络正常
        var mLeftTime2ShopScreenDisposable: Disposable? = null
        var mAskNetworkDisposable: Disposable? = null
        var mCurLeftTime = 0L;

        private fun d(msg: String) {
            CommUtils.println("AppService->", msg)
        }

        fun startAppService(context: Context) {
//            context.startService(Intent(context, AppService::class.java))
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(Intent(context, AppService::class.java));
            } else {
                context.startService(Intent(context, AppService::class.java))
            }
        }
    }

    @SuppressLint("ServiceCast")
    override fun onCreate() {
        super.onCreate()
        BannerApi.initBannerApi()
        startForeground()
    }

    /**
     * 设置服务在前台可见
     */
    //private var notificationChannel:NotificationChannel?=null
    private fun startForeground() {
        /**
         * 创建Notification
         */
        val notificationChannel: NotificationChannel
        val notification: Notification
        var pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, LoginActivity::class.java), 0)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationChannel = NotificationChannel(
                applicationContext.packageName,
                this::class.java.name, NotificationManager.IMPORTANCE_HIGH
            )
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            notificationChannel.setShowBadge(true)
            notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(notificationChannel)
            notification = Notification.Builder(this, "123")
                .setContentTitle(getString(R.string.app_name))
                .setContentTitle(getString(R.string.app_name))
                .setChannelId(applicationContext.packageName)
                //.setSmallIcon(R.mipmap.logo)
                .setContentIntent(pendingIntent)
                .build()
        } else {
            notification = Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentTitle(getString(R.string.app_name))
                //.setSmallIcon(R.drawable.sym_call_incoming)
                .setContentIntent(pendingIntent)
                .build()
        }
        /**
         * 设置notification在前台展示
         */
        startForeground(1, notification)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        d("onStartCommand")
        if (!EventBus.getDefault().isRegistered(this)) EventBusUtil.register(this)
        pollingLeftTime2ShopScreen()
        pollingAskNetwork()
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder? {
        d("onBind")
        return null
    }

    override fun onDestroy() {
        BannerApi.cancelPollingUploadBannerStatistical()
        BannerApi.cancelPollingGetBanner()
        mLeftTime2ShopScreenDisposable?.dispose()
        mAskNetworkDisposable?.dispose()
        EventBusUtil.unregister(this)
        stopForeground(true)
        super.onDestroy()
    }

    @SuppressLint("CheckResult")
    private fun pollingLeftTime2ShopScreen() {
        mLeftTime2ShopScreenDisposable?.dispose()
        Observable.create(ObservableOnSubscribe<String> { e ->
            try {
                val runLoginScreen = ActivityUtils.isRunLoginScreen()
                val runBannerScreen = ActivityUtils.isRunBannerScreen()
                when {
                    //登陆界面跳转广告显示
                    mCurLeftTime % BannerActivity.T2 == 0L && runLoginScreen && (BannerActivity.mBannerImageList.isNotEmpty() || BannerActivity.mBannerVideoList.isNotEmpty()) -> {
                        mCurLeftTime = 0
                        EventBusUtil.sendEvent(Event(EventCode.GO_TO_BANNER_SCREEN))
                    }
                    //广告跳转商户显示屏
                    mCurLeftTime % BannerActivity.T3 == 0L && runBannerScreen -> {
                        mCurLeftTime = 0
                        EventBusUtil.sendEvent(Event(EventCode.BANNER_GO_TO_SHOP_SCREEN))
                    }
                }
                //检查更新
                if (mCountUpdateApp % App.mRequestUpdateTime == 0L) CommUtils.checkUpdateApp { }
                d("mCurLeftTime:$mCurLeftTime;runLoginScreen:$runLoginScreen;runBannerScreen:$runBannerScreen;update:${mCountUpdateApp % App.mRequestUpdateTime},T2:${BannerActivity.T2},T3:${BannerActivity.T3},s2:${mCurLeftTime % BannerActivity.T2},s3:${mCurLeftTime % BannerActivity.T3}")
            } catch (exc: Exception) {
                d("pollingLeftTime2ShopScreen:$exc")
            }
            mCurLeftTime++
            mCountUpdateApp++
            e.onComplete()
        })
            .repeatWhen { return@repeatWhen it.flatMap { return@flatMap Observable.timer(1, TimeUnit.SECONDS) } }
            .compose(RxUtils.nThread())
            .subscribe(object : Observer<String> {
                override fun onComplete() {}
                override fun onSubscribe(d: Disposable) {
                    mLeftTime2ShopScreenDisposable = d
                }

                override fun onNext(t: String) {}
                override fun onError(e: Throwable) {}
            })
    }

    @SuppressLint("CheckResult")
    private fun pollingAskNetwork() {
        mAskNetworkDisposable?.dispose()
        Observable.create(ObservableOnSubscribe<String> { e ->
//            NetworkUtils.isAvailableByPingAsync(App.mDnsIp) {
//                mIsNetworkConnect = it
//                EventBusUtil.sendEvent(Event(EventCode.NET_WORK_STATUES, mIsNetworkConnect))
//                e.onComplete()
//            }
            mIsNetworkConnect = NetworkUtils.isAvailableByPing() || NetworkUtils.isAvailableByPing("180.76.76.76") || NetworkUtils.isAvailableByPing("114.114.114.114")
            EventBusUtil.sendEvent(Event(EventCode.NET_WORK_STATUES, mIsNetworkConnect))
            e.onComplete()
        })
            .repeatWhen { return@repeatWhen it.flatMap { return@flatMap Observable.timer(10, TimeUnit.SECONDS) } }
            .compose(RxUtils.io())
            .subscribe(object : Observer<String> {
                override fun onComplete() {}
                override fun onSubscribe(d: Disposable) {
                    mAskNetworkDisposable = d
                }

                override fun onNext(t: String) {}
                override fun onError(e: Throwable) {}
            })
    }


    fun playSound(soundData: SoundData) {
        if (soundData.money != null)
            VoicePlay.with(this).play(soundData.money, soundData.start)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBusCome(event: Event<Any>?) {
        //d("EventCode:${event?.code}")
        when (event?.code) {
            TOAST_MESSAGE -> ToastUtil.showToast(event.data as String)
            EventCode.VOICE_MSG -> {
                var propellingMessage = event.data as PropellingMessage
                val moneyMsg = propellingMessage.msg
                CommUtils.println("JPushInterface.getAlias:", "moneyMsg:$moneyMsg")
                when {
                    moneyMsg?.contains("支付宝") == true -> playSound(SoundData(VoiceConstants.SUCCESS_ALI_PAY, moneyMsg))
                    moneyMsg?.contains("微信") == true -> playSound(SoundData(VoiceConstants.SUCCESS_WECHAT_PAY, moneyMsg))
                    else -> playSound(SoundData(VoiceConstants.SUCCESS_OTHER_PAY, moneyMsg))
                }
            }
            else -> {}
        }
    }
}